//
//  PPMusicListViewController.m
//  pickpic
//
//  Created by 胡文广 on 2017/10/3.
//  Copyright © 2017年 MicroDream. All rights reserved.
//

#import "PPMusicListViewController.h"
#import "PPMusicModel.h"
#import "PPSongModel.h"
#import <AVFoundation/AVFoundation.h>
#import "JCDownloadOperation.h"
#import "PPMusiclistHeaderView.h"
@interface PPMusicListViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong) UITableView *tableView;

@property (nonatomic,strong) NSMutableArray *musicList;
@property (nonatomic,strong) JCDownloadOperation *operation;
@property (nonatomic,strong) AVPlayerLayer *playerLayer;
@property (nonatomic,strong) AVPlayer *player;
@property (nonatomic,strong) UIView *headerView;
@property (nonatomic,assign) NSIndexPath *currentSelectIndexPath;
@property (nonatomic,strong) PPMusiclistHeaderView *listheaderView;

@property (nonatomic,copy) NSString *currentSongID;
@end

@implementation PPMusicListViewController
- (PPMusiclistHeaderView *)listheaderView{
    
    if (!_listheaderView) {
        _listheaderView = [[NSBundle mainBundle] loadNibNamed:@"PPMusiclistHeaderView" owner:nil options:nil][0];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickTap)];
        
        [_listheaderView addGestureRecognizer:tap];
    }
    return _listheaderView;
}
- (void)clickTap{
    
    BOOL isHidden = self.listheaderView.checkImage.hidden;
    if (self.listheaderView.checkImage.hidden) {
        for (int i = 0; i< self.musicList.count; i++) {
            PPMusicModel *musicModel = self.musicList[i];
            
            for (int j = 0; j< musicModel.songs.count; j++) {
                PPSongModel *songM  = musicModel.songs[j];
                songM.selected = NO;
            }
        }
        isHidden = NO;
    }
    [self.tableView reloadData];
    self.listheaderView.checkImage.hidden = isHidden;
    self.currentSelectIndexPath = nil;
    
    
}
- (NSMutableArray *)musicList{

    if (!_musicList) {
        _musicList = [NSMutableArray array];
    }
    return _musicList;
}
- (void)loadView{

    _tableView = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStylePlain];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.tableFooterView = [[UIView alloc] init];
    self.view = _tableView;
}
- (void)accomplish{

    
    if (self.musicList.count <= 0) {
        return;
    }
    
    
    if (self.currentSongID && !self.listheaderView.checkImage.hidden) {
        //清除音乐
        
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
        hud.mode = MBProgressHUDModeIndeterminate;
        hud.labelText = @"正在删除音乐...";
        [hud show:YES];
        [PPNetworkService musicDELETEEbookWithparams:self.albumHomeModel.albumID callback:^(id data, NSError *error) {
            if (error == nil) {
                [self deleteFile:[NSString stringWithFormat:@"%@.mp3",self.albumHomeModel.albumID]];
                hud.mode = MBProgressHUDModeText;
                hud.labelText = @"删除成功";
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    
                    [hud hide:YES];
                    
                    if (self.BlockDeleteBindSuccess) {
                        self.BlockDeleteBindSuccess();
                    }
                    
                    [self.navigationController popViewControllerAnimated:YES];
                    
                });
            }else{
                
                hud.mode = MBProgressHUDModeText;
                hud.labelText = @"删除失败";
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    
                    [hud hide:YES];
                });
            }
        }];
        return;
    }
    
    if (self.currentSelectIndexPath.section > self.musicList.count) {
        return;
    }
    PPMusicModel *musicModel = self.musicList[self.currentSelectIndexPath.section];
    PPSongModel *songM = musicModel.songs[self.currentSelectIndexPath.row];
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
    hud.mode = MBProgressHUDModeIndeterminate;
    hud.labelText = @"正在更换音乐...";
    [hud show:YES];
    [PPNetworkService musicBindEbookWithparams:@{@"ebook_id":@([self.albumHomeModel.albumID  integerValue]),@"music_id":@([songM.ID longLongValue])} callback:^(id data, NSError *error) {
    
        if (error == nil) {
            
            [self deleteFile:[NSString stringWithFormat:@"%@.mp3",self.albumHomeModel.albumID]];
            
                NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
                NSString *documentsDirectory = [paths objectAtIndex:0];
            
            JCDownloadItem *downloadItem = [[JCDownloadItem alloc] init];
            downloadItem.downloadUrl = songM.url;
                NSString *songPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp3",self.albumHomeModel.albumID]];
            
                downloadItem.downloadFilePath = songPath;
                self.operation = [JCDownloadOperation operationWithItem:downloadItem];
                [self.operation startWithProgressBlock:^(NSProgress *progress) {
            
                    //update progress
                } completionBlock:^(NSURL *filePath, NSError *error) {
                    //download operation completion, do something
            
//                    NSString *fullPath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,[NSString stringWithFormat:@"%@.mp3",songM.name]];
                     NSString *fullPath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,[NSString stringWithFormat:@"%@.mp3",self.albumHomeModel.albumID]];
                    PPLog(@"播放地址 = %@",fullPath);
                    hud.mode = MBProgressHUDModeText;
                    hud.labelText = @"更换成功";
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        
                        [hud hide:YES];
                        if (self.BlockBindSuccess) {
                            self.BlockBindSuccess(fullPath);
                        }
                        
                        [self.navigationController popViewControllerAnimated:YES];
                        
                    });
                    
                }];
            
        }else{
            hud.mode = MBProgressHUDModeText;
            hud.labelText = @"绑定失败";
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [hud hide:YES];
            });
        }
        
    }];

    
}
- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    self.listheaderView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 44);
}
-(void)deleteFile:(NSString *)fileName{
    NSFileManager* fileManager=[NSFileManager defaultManager];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    //文件名
    NSString *uniquePath=[[paths objectAtIndex:0] stringByAppendingPathComponent:fileName];
    BOOL blHave=[[NSFileManager defaultManager] fileExistsAtPath:uniquePath];
    if (!blHave) {
        NSLog(@"no  have");
        return ;
    }else {
        NSLog(@" have");
        BOOL blDele= [fileManager removeItemAtPath:uniquePath error:nil];
        if (blDele) {
            NSLog(@"dele success");
        }else {
            NSLog(@"dele fail");
        }
        
    }
}
- (void)popViewPreviousController{
    [self.playerLayer removeFromSuperlayer];
    self.playerLayer=nil;
    self.player=nil;
    [super popViewPreviousController];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"音乐";
    self.currentSelectIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
//    [self setupBackItem];
    
//    self.navigationItem.leftBarButtonItem = [UIBarButtonItem barButtonItemImageIcon:@"nav_back" leftMargin:25 target:self action:@selector(popViewPreviousController)];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"nav_back"] style:UIBarButtonItemStylePlain target:self action:@selector(popViewPreviousController)];
    self.navigationItem.leftBarButtonItem.tintColor = BLACK;
    
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStyleDone target:self action:@selector(accomplish)];
    
    [PPNetworkService musicListWithparams:@{@"ebook_id":self.albumHomeModel.albumID} callback:^(id data, NSError *error) {
        
        PPLog(@"---%@ -- %@",data,error);
        
        if (error == nil) {
            
            if (self.musicList.count <= 0) {
                self.tableView.tableHeaderView = self.listheaderView;
                self.listheaderView.checkImage.hidden = YES;
                self.tableView.tableHeaderView.height = 44;
            }
            
            NSArray *list = data;
            
            for (NSDictionary *dictMusic in list) {
                
                PPMusicModel *musicModel = [PPMusicModel yy_modelWithDictionary:dictMusic];
                if (!musicModel.songs) {
                    musicModel.songs = [NSMutableArray array];
                }
                if (dictMusic[@"list"]) {
                    NSArray *songs = dictMusic[@"list"];
                    for (NSDictionary *songDict in songs) {
                        PPSongModel *songModel = [PPSongModel yy_modelWithDictionary:songDict];

//                        if ([@"5" isEqualToString:songModel.ID]) {
//                            songModel.select = YES;
//                        }
//                        
                        if (songModel.selected) {
                            self.currentSongID = songModel.ID;
                        }
                        [musicModel.songs addObject:songModel];
                    }
                }
                
                [self.musicList addObject:musicModel];
            }

            [self.tableView reloadData];

        }
        
    }];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

    return self.musicList.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
//    for (PPMusicModel *musicModel in self.musicList) {
//        return musicModel.songs.count;
//    }
    PPMusicModel *musicModel = self.musicList[section];
    return musicModel.songs.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    static NSString *rid=@"cell";
    
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:rid];
    
    if(cell==nil){
        
        cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault      reuseIdentifier:rid];
        cell.tintColor = BLACK;
        
    }
    PPMusicModel *musicModel = self.musicList[indexPath.section];
    PPSongModel *songM = musicModel.songs[indexPath.row];
    cell.textLabel.text = songM.name;
    cell.accessoryType = songM.selected? UITableViewCellAccessoryCheckmark : UITableViewCellAccessoryNone;
    return cell;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

    
    PPMusicModel *musicModel = self.musicList[section];
    
    UIView *headerSection = [[UIView alloc] init];
    headerSection.backgroundColor = COLORA(249, 249, 249);
    headerSection.frame = CGRectMake(0, 0, self.view.width, 30);
    
    UILabel *typeView = [[UILabel alloc] init];
    typeView.frame = CGRectMake(16, 0, 40, 30);
    typeView.font = PFFontBold(16);
    typeView.text = musicModel.type;
    [headerSection addSubview:typeView];
    
    UILabel *countLabel = [[UILabel alloc] init];
    countLabel.frame = CGRectMake(CGRectGetMaxX(typeView.frame),4, 40, 25);
    countLabel.font = PPFONTSIZE(14);
    countLabel.textColor = [UIColor lightGrayColor];
    countLabel.text = [NSString stringWithFormat:@"%zd首",musicModel.count];
    [headerSection addSubview:countLabel];
    
    return headerSection;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{

    return 30;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    self.listheaderView.checkImage.hidden = YES;
    
    PPMusicModel *musicModel = self.musicList[indexPath.section];
    PPSongModel *songM = musicModel.songs[indexPath.row];
    
    //选中处理
    if (!songM.selected) {
        
//        if (self.player) {
//            [self.player pause];
//        }
        
        for (PPMusicModel *musicM in self.musicList) {
            
            for (PPSongModel *song in musicM.songs) {
                
                if ([song.ID isEqualToString:songM.ID]) {
                    
                    song.selected = YES;
                }else{
                    song.selected = NO;
                }
                
            }
        }
        [self.tableView reloadData];
        
    }
 
    self.currentSelectIndexPath = indexPath;
    
//    JCDownloadItem *downloadItem = [[JCDownloadItem alloc] init];
//    downloadItem.downloadUrl = songM.url;
//    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//    NSString *documentsDirectory = [paths objectAtIndex:0];
//    NSLog(@"mp3 path=%@",documentsDirectory);
//    
//    NSString *songPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp3",songM.name]];
//    downloadItem.downloadFilePath = songPath;
//    self.operation = [JCDownloadOperation operationWithItem:downloadItem];
//    [self.operation startWithProgressBlock:^(NSProgress *progress) {
//        
//        //update progress
//    } completionBlock:^(NSURL *filePath, NSError *error) {
//        //download operation completion, do something
//    
//        NSString *fullPath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,[NSString stringWithFormat:@"%@.mp3",songM.name]];
//        
//        PPLog(@"播放地址 = %@",fullPath);
//        NSURL *videoURL = [NSURL fileURLWithPath:fullPath];
//        self.player = [AVPlayer playerWithURL:videoURL];
//        self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
//        
//        if (!self.playerLayer) {
//            self.playerLayer .frame = self.view.bounds;
//            [self.view.layer addSublayer:self.playerLayer];
//        }
//        [self.player play];
//    }];

    
}
@end
